package com.clq.core;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Created by clq on 2019/1/5.
 */
@Component
public class ExchangerTrigger implements ApplicationContextAware{
    Logger logger = LoggerFactory.getLogger(ExchangerTrigger.class);

    private ApplicationContext ctx = null;

    public void trigger() {
        Scheduler scheduler = null;
        try {
            scheduler = StdSchedulerFactory.getDefaultScheduler();
        } catch (SchedulerException e) {
            logger.error("初始化scheduler失败{}", e);
            return;
        }
        for (AbstractExchanger exchanger : ctx.getBeansOfType(AbstractExchanger.class).values()) {
            if(exchanger.getStatus()) {
                JobDetail jobDetail = JobBuilder.newJob(exchanger.getClass())
                        .withIdentity(exchanger.toString() + "Job").build();

                CronTrigger build = TriggerBuilder.newTrigger().withIdentity(TriggerKey.triggerKey(exchanger.toString() + "Trriger"))
                        .withSchedule(CronScheduleBuilder.cronSchedule(exchanger.getCron()))
                        .build();
                try {
                    scheduler.scheduleJob(jobDetail, build);
                } catch (SchedulerException e) {
                    logger.error("添加定时任务失败,{}", e);
                }
                try {
                    scheduler.start();
                } catch (SchedulerException e) {
                    logger.error("启动任务失败 {}", e);
                }

            }
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
        this.trigger();
    }
}
